<template>
  <div class="box" ref="targetElement">
    <div class="search-box" ref="searchBox">
      <div class="search-top-box">
        <div class="search-top-left-box">
          <el-form label-width="110px" ref="div" :inline="true" :model="formSearch" @submit.native.prevent
            class="demo-form-inline">
            <el-form-item label="报价单编号">
              <el-input @change="onSearch(1)" clearable class="form-width" v-model="formSearch.quotation_num"
                placeholder="输入报价单编号"></el-input>
            </el-form-item>
            <el-form-item label="关联采购合同">
              <el-select filterable clearable @change="onSearch(1)" v-model="formSearch.contract_id" placeholder="选择关联采购合同"
                class="form-width">
                <el-option v-for="item in contractList" :key="item.Id" :label="item.contract_name" :value="item.Id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间">
              <el-date-picker class="form-width" @change="onSearch(1)" value-format="yyyy-MM-dd"
                v-model="formSearch.timeDate" type="daterange" range-separator="至" start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="创建人">
              <el-select filterable clearable @change="onSearch(1)" v-model="formSearch.user_id" placeholder="选择创建人"
                class="form-width">
                <el-option v-for="item in adminList" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div class="search-top-right-box">
          <!-- <p @click="moreSearchFunc">
            {{ moreSearchShow ? "收起" : "展开"
            }}<i :class="moreSearchShow ? 'el-icon-arrow-up' : 'el-icon-arrow-down'
              "></i>
          </p> -->
          <el-button type="primary" @click="onSearch(1)">查询</el-button>
          <el-button type="primary" @click="addFunc" v-if="$isPer(permission, ['quotation_add'])">新增报价单</el-button>
        </div>
      </div>
    </div>
    <!-- table -->
    <div class="page-list" ref="pageList">
      <div class="list-top-box">
        <p class="list-top-box-left">
          已选<span class="num">{{ multipleSelection.length }}</span>/{{ tableData.length }}数据
        </p>
        <div class="list-top-box-right">
          <el-button type="primary" :disabled="multipleSelection.length != 1" @click="editFunc"
            v-if="$isPer(permission, ['purchase_updateQuotation'])">编辑</el-button>
          <el-button type="danger" plain :disabled="multipleSelection.length == 0" @click="delFunc"
            v-if="$isPer(permission, ['purchase_deleteQuotation'])">删除</el-button>
        </div>
      </div>
      <div class="table-box" v-loading="tableLoading">
        <el-table ref="table" border :header-cell-style="{
          background: '#FAFBFC',
          color: '#828A9D',
          textAlign: 'center',
        }" :cell-style="{ textAlign: 'center', color: '#1B2431' }" :data="tableData"
          @selection-change="handleSelectionChange" @row-click="handleHighlightChangeTable" highlight-selection-row
          height="100%">
          <el-table-column type="selection" width="80"></el-table-column>
          <el-table-column v-if="$fieldShowFunc('bjd_bjdbh')" min-width="180px" prop="quotation_num" label="报价单编号" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-button v-if="scope.row.quotation_num" type="text" @click.stop="goToDetail(scope.row)">{{
                scope.row.quotation_num || '--'
              }}</el-button>
              <span v-else>{{ scope.row.quotation_num || '--' }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('bjd_glcght')" min-width="180px" prop="contract_name" label="关联采购合同" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.contract_name || "--" }}
            </template>
          </el-table-column>
          <!-- <el-table-column min-width="180px" prop="project_name" label="产品规格名称" show-overflow-tooltip>
          </el-table-column>
          <el-table-column min-width="180px" prop="project_name" label="采购单价（不含税）" show-overflow-tooltip>
          </el-table-column>
          <el-table-column min-width="180px" prop="project_name" label="采购单价（含税）" show-overflow-tooltip>
          </el-table-column>
          <el-table-column min-width="180px" prop="project_name" label="税率" show-overflow-tooltip>
          </el-table-column> -->
          <el-table-column v-if="$fieldShowFunc('bjd_cjsj')" min-width="180px" prop="created_at" label="创建时间" show-overflow-tooltip>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('bjd_cjr')" min-width="180px" prop="name" label="创建人" show-overflow-tooltip>
          </el-table-column>
        </el-table>
      </div>
      <div class="page-footer">
        <el-pagination class="el-pagination" @current-change="handleCurrentChange" :current-page="page" :page-size="num"
          @size-change="handleSizeChange" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>
    <!-- 报价单详情 -->
    <el-dialog title="详情" :visible.sync="deetailVisible" width="800px" :modal-append-to-body="false">
      <div class="detail-box">
        <div class="descriptions">
          <el-descriptions title="" border>
            <el-descriptions-item v-if="$fieldShowFunc('bjd_bjdbh')" label="报价单编号">{{ detailData.quotation_num }}</el-descriptions-item>
            <el-descriptions-item v-if="$fieldShowFunc('bjd_glcght')" label="采购合同">{{ detailData.contract_name }}</el-descriptions-item>
            <el-descriptions-item v-if="$fieldShowFunc('bjd_bjdzt')" label="报价单状态">{{ detailData.state == 1 ? '生效' : '失效' }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <el-table :data="detailData.specs_list" border :header-cell-style="{
          background: '#FAFBFC',
          color: '#828A9D',
          textAlign: 'center',
        }" :cell-style="{ textAlign: 'center', color: '#1B2431' }" highlight-selection-row height="100%">
          <el-table-column v-if="$fieldShowFunc('bjd_cpggmc')" min-width="180px" prop="product_specs_name" label="产品规格名称" show-overflow-tooltip>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('bjd_cgdjbhs')" min-width="180px" prop="unit_price" label="采购单价（不含税）" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.unit_price + '元' }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('bjd_cgdjhs')" min-width="180px" prop="unit_price_tax" label="采购单价（含税）" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.unit_price_tax + '元' }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('bjd_sl')" min-width="180px" prop="tax_rate" label="税率" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.tax_rate + '%' }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import commonApi from "@/api/common";
import { getUserInfo } from "@/utils/auth";
import purchaseApi from "@/api/purchaseApi";
import adminApi from "@/api/adminApi";
export default {
  name: "quotationManagement",
  components: {},
  data() {
    return {
      deetailVisible: false,
      detailData: {},
      tableLoading: false,
      userInfo: "",
      tableData: [],
      formSearch: {
        timeDate: "",
        quotation_num: "",
        contract_id: "",
        user_id: "",
      },
      moreSearchShow: false,
      page: 1,
      num: 10,
      total: 0,
      multipleSelection: [],
      contractList: [],//合同列表
      adminList: [],//用户列表
      permission: [],//操作权限
    };
  },
  watch: {},
  computed: {},
  activated() {
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.handleResize);
    this.onSearch();
  },
  destroyed() {
    window.removeEventListener('resize', this.handleResize);
    // 移除窗口大小变化事件监听器，防止内存泄漏
    if (this.resizeObserver) {
      // 停止观察目标元素，防止内存泄漏
      this.resizeObserver.disconnect();
    }
  },
  deactivated() {
    window.removeEventListener('resize', this.handleResize);
    // 移除窗口大小变化事件监听器，防止内存泄漏
    if (this.resizeObserver) {
      // 停止观察目标元素，防止内存泄漏
      this.resizeObserver.disconnect();
    }
  },
  mounted() {
    this.handleResize();
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.handleResize);
    // 操作权限
    this.$getHtmlAuthority(this.$route.path).then(res => {
      console.log(res, "getHtmlAuthority");
      this.permission = res.data.permission;
    })
    this.userInfo = getUserInfo();
    this.getQuotation();//报价单列表
    this.getContract();//合同列表
    this.getAdminList();//用户列表
  },
  methods: {
    handleResize() {
      const target = this.$refs.targetElement;
      const searchBox = this.$refs.searchBox;
      const pageList = this.$refs.pageList;
      // 创建 ResizeObserver 实例
      const resizeObserver = new ResizeObserver(entries => {
        setTimeout(() => {
          console.log('元素变为:', searchBox.offsetHeight);
          // searchBox.offsetHeight + 'px'
          pageList.style.height = 'calc(100% - ' + (searchBox.offsetHeight + 15) + 'px)';
        }, 0);
      });
      // 开始观察目标元素
      resizeObserver.observe(target);

      // 存储 resizeObserver 实例，以便在组件销毁时停止观察
      this.resizeObserver = resizeObserver;
    },
    // 查看详情
    goToDetail(item) {
      purchaseApi.getQuotationInfo({
        quotation_id: item.Id
      }).then(res => {
        console.log(res, '报价单详情')
        if (res.code == 200) {
          this.detailData = res.data;
          this.deetailVisible = true;
        }
      })
    },
    // ----------------------------编辑按钮----------------------------
    editFunc() {
      let multipleSelection = this.multipleSelection;
      this.$store.commit('isEventTriggeredFunc', true);
      this.$router.push({
        path: "/addQuotation",
        query: {
          id: multipleSelection[0].Id,
          route_title: '编辑报价单'
        }
      })

    },
    // ----------------------------删除按钮----------------------------
    delFunc() {
      let multipleSelection = this.multipleSelection;
      this.$confirm('此操作将永久删除已勾选报价单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let delete_arr = [];
        multipleSelection.forEach(item => {
          delete_arr.push(item.Id);
        })
        purchaseApi.deleteQuotation({ delete_arr }).then(res => {
          console.log(res, "删除报价单")
          if (res.code == 200) {
            this.onSearch();
          }
          this.$message({
            type: res.code == 200 ? 'success' : 'warning',
            message: res.message
          })
        })
      }).catch(() => { });
    },
    // ----------------------------table点击行-选中----------------------------
    handleHighlightChangeTable(row) {
      if (!row.disabled) {
        this.$refs.table.toggleRowSelection(row);
      }
    },
    // 报价单列表
    getQuotation() {
      this.tableLoading = true;
      let formSearch = this.formSearch;
      purchaseApi.getQuotation({
        page: this.page,
        num: this.num,
        start_time: formSearch.timeDate ? formSearch.timeDate[0] : "",
        end_time: formSearch.timeDate ? formSearch.timeDate[1] : "",
        quotation_num: formSearch.quotation_num,
        contract_id: formSearch.contract_id,
        user_id: formSearch.user_id,

      }).then(res => {
        console.log(res, "报价单列表")
        this.tableLoading = false;
        if (res.code == 200) {
          this.tableData = res.data.list;
          this.total = res.data.max;
        }
      })
    },
    // 合同列表
    getContract() {
      purchaseApi.getContract({
        page: 1,
        num: 999
      }).then(res => {
        console.log(res, "合同列表")
        if (res.code == 200) {
          this.contractList = res.data.list;
        }
      })
    },
    // 用户列表
    getAdminList() {
      adminApi.getAdminList({
        identity: 1,
        page: 1,
        num: 999
      }).then(res => {
        console.log(res, "用户列表")
        if (res.code == 200) {
          this.adminList = res.data.list;
        }
      })
    },
    // 单页数据量修改
    handleSizeChange(e) {
      this.num = e;
      this.onSearch(1);
    },
    // 页面权限
    getHtmlAuthority() {
      commonApi
        .getHtmlAuthority({
          path: this.$route.path,
        })
        .then((res) => {
          console.log(res, "页面权限");
          if (res.code == 200) {
            this.HtmlAuthority = res.data;
          }
        });
    },
    // 搜索
    onSearch(page) {
      this.page = typeof page == 'number' ? page : this.page;
      this.getQuotation();
    },
    // 翻页
    handleCurrentChange(page) {
      this.onSearch(page);
    },
    moreSearchFunc() {
      this.moreSearchShow = !this.moreSearchShow;
      this.$nextTick(() => {
        this.handleResize();
      })
    },
    addFunc() {
      this.$store.commit('isEventTriggeredFunc', true);
      this.$router.push({
        path: "/addQuotation",
        query: {
          route_title: '新增报价单'
        }
      })
    },
    handleSelectionChange(e) {
      console.log(e);
      this.multipleSelection = e;
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./index.scss";
@import '@/styles/listPage.scss';
</style>